<template>
    <div class="abnormal">
        <div class="flex-header">
            <my-header title="路试取车" />
        </div>
        <div class="content-box">
            <mu-text-field v-model="vin" v-if="isShowVin" @blur="" placeholder="VIN" ref="vin" class='input'
                @keyup.enter.native="getConfigData(1)"><i class="iconfont icon-saomiao"
                    @click="scan('vin')"></i></mu-text-field>

            <mu-paper class="paper" v-if="isShowPaper" :z-depth="2">
                <div class="list-content">单号：<span>{{ code }}</span></div>
                <div class="list-content">VIN：<span>{{ reqestVin }}</span></div>
                <div class="list-content">类型：<span>{{ type }}</span></div>
                <div class="list-content">线路：<span>{{ route }}</span></div>
            </mu-paper>

            <!--图片全屏预览-->
            <mu-dialog width="360" transition="slide-bottom" fullscreen :open.sync="openFullscreen">
                <mu-appbar color="" title="">
                    <mu-button slot="right" flat @click="closeFullscreenDialog">关闭</mu-button>
                </mu-appbar>
                <div id='ylbox'>
                    <mu-carousel :cycle="false">
                        <mu-carousel-item>
                            <img :src="bigImg">
                        </mu-carousel-item>
                    </mu-carousel>
                </div>
            </mu-dialog>

            <div class="photos" v-if="isShowPhoto">
                <div class="imgs" v-for="(item, index) in src" :key="index" @touchstart.stop="touchin(index)"
                    @touchend.stop="cleartime()" @click.stop="openFullscreenDialog(index)">
                    <img :src="item">
                </div>
                <i class="iconfont icon-icon25201" @click="paizhao"></i>
            </div>

            <mu-dialog width="320" max-width="60%" :open.sync="openAlert">
                确认删除图片?
                <mu-button slot="actions" flat color="primary" @click="closeAlertDialog('n')">取消</mu-button>
                <mu-button slot="actions" flat color="primary" @click="closeAlertDialog('y')">删除</mu-button>
            </mu-dialog>

            <div class="fl" v-if="isShowBtn">
                <mu-button color="primary" class="submit" @click='PhotoSend' large>上传凭证</mu-button>
                <mu-button color="primary" class="submit" @click='submit(1)' large>确认完成</mu-button>
            </div>
        </div>
        <scanning v-if="isScanning" :mark="scanMark" v-on:childByValue="childByValue" v-on:closeing="closeing" />
    </div>
</template>

<script>
import myHeader from "@/components/header"
import scanning from "@/components/scanning"
import api from "@/common/api"
export default {
    components: {
        myHeader, scanning
    },
    data() {
        return {
            accuracy: 65,
            isScanning: false,
            scanMark: '',
            openFullscreen: false,
            Loop: null,
            deleteIndex: null, // 删除第几张
            openAlert: false, // 删除图片层
            isShowPaper: false, // 显示新西兰
            isShowPhoto: false, // 显示照片
            isShowBtn: false, // 显示按钮
            isShowVin: true, // 显示vin
            text: '', // 备注
            vin: '', // vin
            car: '', // 车型
            color: '', // 颜色
            code: '', // 单号
            lng: 0,
            lat: 0,
            reqestVin: '', // 任务vin
            type: '', // 类型
            route: '', // 路线
            isScan: true,
            open1: false, // 底部 类型选择框
            open2: false, // 底部 原因选择框
            abnormalType: "", // 类型 页面显示
            abnormalReas: "", // 原因 页面显示
            abnormalTypeArr: [], // 异常类型
            abnormalReasArrX: [], // 原因选择
            abnormalReasArr: [], // 异常原因
            src: [], // 拍照的图片
            files: [], // 图片文件 base64
            bigImg: null,
            routeLine: [], // 规定行驶路线
            otherTaskTo: false,
            isBeginStay: false, // 是否开始停留
            stayTime: 0,
            initSpeeds: 0,
            limitNum: 5, // 电子围栏半径
            maxStayTime: 30, // 最大停留时间 (分钟)
            stayIntalval: null, // 停留定时器
            preLeaveTime: 0, // 上次上报偏移时的时间戳
            preSpeedingTime: 0, // 上次上报超速时的时间戳
            trajectoryPlan: [],
            defaultSpeed: 2,
            taskId: 0,
            watchMark: false,
            CurrentSection: 0, // 当前路段
            thePreSPD: 0, // 上一个路段限速
            py: 50,
            islocked: true
        }
    },
    methods: {
        PhotoSend() {
            if (this.files.length == 0) {
                this.Toast.loading({ mask: true, message: '请先拍照，再上传~！' });
                return false;
            }

            if (this.$store.state.latitude - 1 == -1 || this.$store.state.longitude - 1 == -1) {
                this.Toast.loading({ mask: true, message: '当前无定位，无法上传~！' });
                return false;
            }
            // 提示
            this.Toast.loading({ mask: true, message: '提交中...' });
            let data = Object.assign({}, this.$store.state.user, {
                content: {
                    img: this.files,
                    stayTime: this.stayTime,
                    stayLoc: this.$store.state.addresses,
                    lng: this.$store.state.longitude,
                    lat: this.$store.state.latitude
                }
                //  img图片内容、停留时间stayTime、停留位置stayLoc、经度lng、纬度lat
            });
            console.log("图二：", JSON.stringify(this.files));
            this.common.reqData(api.app('uploadImg'), data, res => {
                if (res.data.status == 100) {
                    this.Toast.success({
                        message: '提交成功'
                    });
                    // 提交成功后 全部制空
                    this.src = [];
                    this.files = [];
                } else {
                    this.Toast({
                        message: res.data.msg
                    });
                }
            }, err => {
                console.log(err)
            });
        },
        touchin(index) {
            var _this = this;
            clearInterval(this.Loop); //再次清空定时器，防止重复注册定时器
            this.Loop = setTimeout(function () {
                _this.deleteImgDialog(index);
            }.bind(this), 500);
        },
        cleartime(id, course_id) {
            // 这个方法主要是用来将每次手指移出之后将计时器清零
            clearInterval(this.Loop);
        },
        openFullscreenDialog(index) {
            this.bigImg = this.src[index];
            this.openFullscreen = true;
        },
        closeFullscreenDialog() {
            this.openFullscreen = false;
        },
        closeing(val) {
            val ? this.isScanning = false : null;
        },
        childByValue(val) {
            if (val) {
                if (val.split('&')[1] == 'vin') {
                    this.vin = val.split('&')[0];
                }
            }
            this.getConfigData(0);
        },
        scan(txt) {
            this.scanMark = txt;
            this.isScanning = true;
        },
        getConfigData(way) {
            // 请求vin数据common.appApi.abnormalVinQuery
            /* 发送post请求 */
            console.log("this.taskId", this.taskId);
            if (this.islocked) {
                this.islocked = false;
                let data = Object.assign({}, this.$store.state.user, {
                    content: {
                        vin: this.vin,
                        getWay: way,
                        taskId: this.taskId
                    }
                });
                this.common.reqData(api.app('getCar'), data, res => {
                    console.log(res.data);
                    if (res.data.status == 100) {
                        this.isShowVin = false,
                            this.isShowPhoto = true,
                            this.isShowBtn = true;
                        this.watchMark = res.data.content.isControl ? res.data.content.isControl : false;
                        this.initReqestData();
                    } else {
                        // 提示
                        this.Toast({
                            message: res.data.msg
                        });
                    }
                    this.islocked = true;
                }, err => {
                    this.islocked = true;
                });
            }
        },
        deleteImgDialog(index) {
            // 删除图片 打开
            this.deleteIndex = index;
            this.openAlert = true;
        },
        closeAlertDialog(state) {
            // 删除图片 关闭
            if (state === 'y') {
                this.src.splice(this.deleteIndex, 1);
                this.files.splice(this.deleteIndex, 1);
            }
            this.openAlert = false;
        },
        choiceAbType(item, index) {
            this.abnormalType = item.name;
            this.abnormalReas = "";
            this.open1 = false;
            this.abnormalReasArrX = this.abnormalReasArr[index];
        },
        choiceAbReas(item, index) {
            this.abnormalReas = item.name;
            this.open2 = false;
        },
        done() {
            // 提示
            this.Toast.loading({
                mask: true,
                message: '提交中...'
            });
            this.common.reqData(api.app('arriveConfirm'), this.$store.state.user, res => {
                if (res.data.status == 100) {
                    console.log("提交完成：", res.data);
                    this.Toast.success({
                        message: '提交成功'
                    });
                    // 提交成功后 全部制空
                    this.vin = "";
                    this.car = "";
                    this.color = "";
                    this.src = [];
                    this.files = [];
                    this.text = "";
                    this.abnormalType = "";
                    this.abnormalReas = "";
                    this.webInitPage(res);
                } else {
                    this.Toast({
                        message: res.data.msg
                    });
                }
            }, err => {
                console.log(err)
            });
        },
        submit(mark) {
            // 判断司机是否在电子围栏半径内，如果是，调用done完成函数
            this.common.distanceCompute({
                latitude: this.lat,
                longitude: this.lng
            }, {
                latitude: this.$store.state.latitude,
                longitude: this.$store.state.longitude
            }, this.limitNum, () => {
                // 在电子围栏半径内
                this.done();
            }, () => {
                console.log("在电子围栏外");
                mark == 1 ? this.Toast({ mask: true, message: '当前定位在电子围栏外，无法完成。' }) : '';
            });
        },
        closeBottomSheet() {
            this.open = false;
        },
        openBotttomSheet(who) {
            who == 'open1' ? this.open1 = true : this.open2 = true;
        },
        onChange(picker, values) {
            picker.setColumnValues(1, citys[values[0]]);
        },
        paizhao() {
            let _this = this;
            if (_this.files.length >= 1) {
                return false;
            }
            if (window.plus) {
                var cmr = plus.camera.getCamera();
                var res = cmr.supportedImageResolutions[0];
                var fmt = cmr.supportedImageFormats[0];
                console.log("Resolution: " + res + ", Format: " + fmt);
                cmr.captureImage(function (path) {
                    plus.io.resolveLocalFileSystemURL(path, function (entry) {
                        // 转化本地绝对路径
                        var url = plus.io.convertLocalFileSystemURL(path);
                        _this.src.push("file://" + url);
                        // 获取图片对象
                        entry.file(function (file) {
                            var fileReader = new plus.io.FileReader();
                            fileReader.onloadend = function (evt) {
                                console.log(evt.target.result);
                                _this.files.push(evt.target.result);
                                console.log("图片一： " + evt.target.result);
                            }
                            fileReader.readAsDataURL(file);
                        });
                    });
                },
                    function (error) {
                        console.log("拍照已经取消: " + error.message);
                    }, { resolution: res, format: fmt });
            }
        },
        uploadSelf(flag, tts, opt) {
            /**
             * 0 偏移 1 超速 2 停留
             */
            tts.length > 0 ? this.common.tts(tts) : '';

            let data = Object.assign({}, this.$store.state.user, {
                content: {
                    taskId: this.taskId,
                    flag: flag, // 标记
                    speedXS: opt && opt.speed ? opt.speed : 0, // 限速
                    py: opt && opt.py ? opt.py : 0,
                    stayTime: this.stayTime, // 停留时间
                    stayLoc: this.$store.state.addresses, // 位置
                    lng: this.$store.state.longitude,
                    speed: Math.floor(this.$store.state.speed), // 超速速度
                    lat: this.$store.state.latitude
                }
                //  img图片内容、停留时间stayTime、停留位置stayLoc、经度lng、纬度lat
            });

            this.common.reqData(api.app('sendStayTime'), data, res => {
                if (res.data.status == 100) {
                    console.log("已成功记录日志");
                    if (flag == 1) {
                        this.webInitPage(res);
                    }
                    if (flag == 2) {
                        this.stayTime = 0;
                    }
                } else {
                    this.Toast({
                        message: res.data.msg
                    });
                }
            }, err => {
                console.log(err)
            });
        },
        queryTask() {
            /**
             * 监控查询任务-判断系统是否手动完成
             */

            let data = Object.assign({}, this.$store.state.user, {
                content: {
                    taskId: this.taskId
                }
                //  img图片内容、停留时间stayTime、停留位置stayLoc、经度lng、纬度lat
            });

            this.common.reqData(api.app('queryTask'), data, res => {
                if (res.data.status == 100) {
                    console.log("查询", JSON.stringify(res.data));
                    this.vin = '';
                    this.webInitPage(res);
                } else {
                    this.Toast({
                        message: res.data.msg
                    });
                }
            }, err => {
                console.log(err)
            });
        },
        WatchingDiver() {
            if (!this.watchMark) return false;
            console.log('监控中...');
            let pt = {
                lng: this.$store.state.longitude,
                lat: this.$store.state.latitude
            };

            this.queryTask();

            let pointArr = [];
            this.trajectoryPlan.forEach((item, index) => {
                pointArr.push(item.point);
            });

            var h = [];
            for (var i = 0; i < pointArr.length - 1; i++) {
                var a = pointArr[i], b = pointArr[i + 1];
                /**
                 * 求三角形的三边长
                 */
                var x = this.common.GetTranslate(a, b);
                var y = this.common.GetTranslate(a, pt);
                var z = this.common.GetTranslate(pt, b);

                var f = x * x + y * y < z * z || x * x + z * z < y * y; // 判断线段为∠是否是钝角三角形

                /**
                 * 根据海伦公式，算出三角形面积
                 */
                var t = (x + y + z) / 2;
                var s = Math.sqrt(t * (t - x) * (t - y) * (t - z));

                /**
                 * 算出高度
                 */
                var mh = 2 * s / x;

                var xs = 100000; // 倍数值

                x > 0 ? f ? h.push(Math.min(z, y) * xs) : h.push(mh * xs) : null;
            }

            // console.log("计划路线点位", JSON.stringify(this.trajectoryPlan));
            // console.log("当前点位", JSON.stringify(pt));
            // console.log("司机到线段高集合：", h);
            // console.log("最小值是：", Math.min.apply(null, h));
            // console.log("当前最小值分段是：", this.common.GetIndex(h, Math.min.apply(null, h)));

            /**
             * 道路偏移
             */

            var spd = this.initSpeeds;
            if (this.trajectoryPlan && this.trajectoryPlan.length > 0) {
                spd = this.trajectoryPlan[this.common.GetIndex(h, Math.min.apply(null, h))].speed;
            }

            if (Math.min.apply(null, h) > this.py && this.trajectoryPlan && this.trajectoryPlan.length > 0) {
                if (((new Date()).getTime()) - this.preLeaveTime >= 25 * 1000) {
                    if (this.$store.state.accuracy > 0 && this.$store.state.accuracy <= this.accuracy && this.$store.state.accuracy) {
                        this.uploadSelf(0, "偏移路段，" + (this.common.GetIndex(h, Math.min.apply(null, h)) + 1) + '，偏移值：' + Math.floor(Math.min.apply(null, h)), {
                            py: Math.floor(Math.min.apply(null, h)),
                            speed: null
                        });
                    }
                    this.preLeaveTime = (new Date()).getTime();
                }
            }

            /**
             * 超速
             */
            if (this.common.GetIndex(h, Math.min.apply(null, h)) !== this.CurrentSection || this.CurrentSection == 0) {
                if (spd !== this.thePreSPD) {
                    this.common.tts("当前限速" + this.trajectoryPlan[this.common.GetIndex(h, Math.min.apply(null, h))].speed);
                    this.CurrentSection = this.common.GetIndex(h, Math.min.apply(null, h)); // 当前路段
                }
                this.thePreSPD = spd;
            }
            if (Math.floor(this.$store.state.speed) > spd && spd !== 0) {
                console.log('进入超速函数11111');
                if (((new Date()).getTime()) - this.preSpeedingTime >= 15 * 1000) {
                    if (this.$store.state.accuracy > 0 && this.$store.state.accuracy <= this.accuracy && this.$store.state.accuracy) {
                        console.log('进入超速函数22222');
                        this.uploadSelf(1, '您已超速，当前限速：' + spd, {
                            py: null,
                            speed: spd
                        });
                    }
                    this.preSpeedingTime = (new Date()).getTime();
                }
            }

            /**
             * 停留开始
             */
            if (!this.isBeginStay && Math.floor(this.$store.state.speed) <= this.defaultSpeed) {
                console.log('---开始停留计时---');
                this.isBeginStay = true;
                this.stayIntalval = setInterval(() => {
                    this.stayTime += 0.1;
                }, 100);
            }

            // if(this.isBeginStay && this.stayTime > this.maxStayTime * 60){
            //     clearInterval(this.stayIntalval);
            //     console.log('停留超过5分钟');
            //     this.isBeginStay = false;
            //     this.uploadSelf(2, '停留超过'+this.maxStayTime+'分钟');
            // }
            // if(this.isBeginStay && Math.floor(this.$store.state.speed) > this.defaultSpeed){
            //     this.stayTime = 0;
            //     this.isBeginStay = false;
            // }
            // if(this.isBeginStay && this.$store.state.speed > this.defaultSpeed){
            //     clearInterval(this.stayIntalval);
            //     if(this.stayTime > this.maxStayTime * 60){
            //         console.log('停留超过5分钟');
            //         this.uploadSelf(2, '停留超过'+this.maxStayTime+'分钟');
            //     }
            // }

        },
        webInitPage(res) {
            if (!res.data.content) return;
            this.watchMark = res.data.content.isControl ? res.data.content.isControl : false;
            this.isScan = res.data.content.isScan ? res.data.content.isScan : false;
            this.trajectoryPlan = res.data.content.trajectoryPlan ? res.data.content.trajectoryPlan : [];
            this.lng = res.data.content.lng ? res.data.content.lng : 0;
            this.lat = res.data.content.lat ? res.data.content.lat : 0;
            this.limitNum = res.data.content.limitNum ? res.data.content.limitNum : 0; // 半径
            this.maxStayTime = res.data.content.maxStayTime ? res.data.content.maxStayTime : 0; // 最大停留时间
            this.py = res.data.content.py ? res.data.content.py : 0;
            this.defaultSpeed = res.data.content.defaultSpeed ? res.data.content.defaultSpeed : 2;
            this.initSpeeds = res.data.content.speed ? res.data.content.speed : 0;
            this.taskId = res.data.content.taskId ? res.data.content.taskId : 0;
            this.code = res.data.content.code ? res.data.content.code : ''; // 单号
            this.reqestVin = res.data.content.vin ? res.data.content.vin : ''; // 任务vin
            this.type = res.data.content.type ? res.data.content.type : ''; // 类型
            this.route = res.data.content.wmsLine ? res.data.content.wmsLine : ""; // 路线
            this.accuracy = res.data.content.accuracy ? res.data.content.accuracy : 65; // 精度大小

            if (res.data.content.isScan) {
                this.isShowVin = true, this.isShowPaper = true,
                    this.isShowPhoto = false, this.isShowBtn = false;
            } else {
                this.isShowVin = false, this.isShowPaper = true,
                    this.isShowPhoto = true, this.isShowBtn = true;
            }
            console.log("res.data.content.cleanPage", res.data.content.cleanPage);
            if (res.data.content.cleanPage) {
                this.isShowPaper = this.isShowPhoto = this.isShowBtn = this.isShowVin = false;
            }
        },
        initReqestData() {
            this.common.reqData(api.app('initTask'), this.$store.state.user, res => {
                console.log(res);
                if (res.data.status === 100) {
                    this.webInitPage(res);
                } else {
                    // 提示
                    this.Toast({ message: res.data.msg });
                }
            }, err => {
            });
        }
    },
    mounted() {
        this.initReqestData();
    },
    beforeDestroy() {
        clearInterval(this.stayIntalval);
    },
    computed: {
        latitudeChange() {
            return this.$store.state.latitude;
        },
        longitudeChange() {
            return this.$store.state.longitude;
        },
        speedChange() {
            return this.$store.state.speed;
        }
    },
    watch: {
        stayTime: function () {
            if (this.isBeginStay && this.stayTime > this.maxStayTime * 60 && Math.floor(this.$store.state.speed) > this.defaultSpeed) {
                clearInterval(this.stayIntalval);
                this.isBeginStay = false;
                this.uploadSelf(2, '停留超过' + Math.floor(this.stayTime / 60) + '分钟');
            }
        },
        latitudeChange: function (data) {
            this.WatchingDiver();
            // this.submit();
        },
        longitudeChange: function (data) {
            this.WatchingDiver();
            // this.submit();
        },
        speedChange: function (data) {
            this.WatchingDiver();
            // this.submit();
        }
    }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.mu-input {
    width: 85%;
    margin: 20px auto 0;
    display: block;
}

.imgs {
    width: 50px;
    height: 50px;
    overflow: hidden;
    margin: 10px;
}

.imgs img {
    width: 100%;
}

.photos {
    border: 1px solid #ccc;
    width: 90%;
    margin: 20px auto 0;
    display: flex;
    flex-wrap: wrap;
    align-items: center;
}

i.iconfont.icon-icon25201 {
    display: block;
    font-size: 50px;
    margin: 10px;
}

.paper {
    width: 90%;
    margin: 20px auto 0;
    padding: 10px 0;
}

.paper div {
    padding: 10px 20px;
}

.submit {
    display: block;
    margin: 20px auto;
}

.abnormal-box {
    width: 90%;
    margin: 0 auto;
    display: flex;
    justify-content: space-around;
}

.abnormal-box .mu-input {
    width: 45%;
}

em {
    padding: 0 2em;
}

.mu-carousel {
    height: 100%;
}

#ylbox {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
}

#ylbox img {
    width: 100%;
    height: 100%;
}

header.mu-appbar {
    box-shadow: none;
    background: none;
    position: absolute;
    width: 100%;
}

.fl {
    display: flex;
}
</style>
